﻿using System;
using System.IO;
using System.Reflection;
using System.Data.Entity;

namespace EntityFrameworkDemo
{
    public class DbCustomInitializerStrategy<T> : IDatabaseInitializer<T> where T : Db
    {
        /// <summary>
        /// Create Database if not exists. Drop data if exists. Install stored procedures.
        /// </summary>
        /// <param name="context"></param>
        public void InitializeDatabase(T context)
        {
            if (!context.Database.Exists())
            {

                ////Create database
                context.Database.Create();

                #region Create from Custom Script

                var currentAssembly = Assembly.GetExecutingAssembly();
                var resourceName = "EntityFrameworkDemo.Install.sql";// string.Format("{0}.Install.sql", currentAssembly.GetName());
                var sr = new StreamReader(currentAssembly.GetManifestResourceStream(resourceName));
                var installSqlScript = sr.ReadToEnd();

                context.Database.ExecuteSqlCommand(installSqlScript, new object[] { });

                #endregion
            }
            else
            {
                context.Database.ExecuteSqlCommand("DELETE FROM ProgettoSviluppatore", new object[] { });
                context.Database.ExecuteSqlCommand("DELETE FROM Competenza", new object[] { });
                context.Database.ExecuteSqlCommand("DELETE FROM Architetto", new object[] { });
                context.Database.ExecuteSqlCommand("DELETE FROM Sviluppatore", new object[] { });
                context.Database.ExecuteSqlCommand("DELETE FROM Progetto", new object[] { });
                context.Database.ExecuteSqlCommand("DELETE FROM Cliente", new object[] { });
            }
        }
    }
}